package com.tensquare.user.service;

import com.tensquare.user.dao.AdminDao;
import com.tensquare.user.pojo.Admin;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import util.IdWorker;

@Service
public class AdminService {

    @Autowired
    private AdminDao adminDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private BCryptPasswordEncoder encoder;


    //1.添加管理员
    public void add(Admin admin) {
        //1.1设置管理员id
        admin.setId(idWorker.nextId()+"");
        //1.2对密码进行加密
        admin.setPassword(encoder.encode(admin.getPassword()));
        //1.3添加到数据库
        adminDao.save(admin);

    }
    //2.管理员登录
    public Admin login(Admin admin) {
        //2.1根据登录名查询管理员
        Admin byLoginname = adminDao.findByLoginname(admin.getLoginname());
        //2.2判断管理员密码是否正确,,正确就返回该管理员对象
        if(byLoginname!=null && StringUtils.isNotBlank(admin.getPassword()) &&
                encoder.matches(admin.getPassword(),byLoginname.getPassword())){
            return byLoginname;
        }
        //2.3返回空
        return null;
    }
    //3.删除管理员
    public void delete(String adminId) {
        adminDao.deleteById(adminId);
    }
}
